/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fsktms.packetmanager;

import fsktms.IPacket;
import java.io.IOException;
import java.net.Socket;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author salm
 */
class PacketManagerImpl
    implements IPacketManager
{
    private Queue<IPacket> packets = new ArrayDeque<>();
    
    private PacketInteractor pi;
    
    public PacketManagerImpl(Socket cl) throws IOException
    {
        pi = new PacketInteractor(cl);
    }
    
    @Override
    public boolean isHasNewPacket()
    {
        return !this.packets.isEmpty();
    }

    @Override
    public IPacket getLastPacket()
    {
        return this.packets.poll();
    }

    @Override
    public void sendPackage(IPacket pkg) throws IOException
    {
        try
        {
            this.pi.SendPkg(pkg);
        }
        catch (IOException ex)
        {
            this.close();
            Logger.getLogger(PacketManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run()
    {   
        pi.run();
        
        while (pi.isHasPkg())
        {
            this.packets.add(pi.GetPkg());
        }
    }

    @Override
    public void close() throws IOException
    {
        this.pi.close();
    }
    
    public boolean isClosed()
    {
        return this.pi.isClosed();
    }

    @Override
    public String getAddress()
    {
        return this.pi.getAddress();
    }
}
